package com.lingkang.ngfile.config.security;

import com.lingkang.ngfile.entity.NgUser;
import com.lingkang.ngfile.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 用户登录成功时返回给前端的数据
 **/
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //返回0 表示成功！
        httpServletResponse.getWriter().write("0");
        //将用户信息放到session中
        User user = (User) authentication.getPrincipal();
        NgUser ngUser = userService.getInfo(user.getUsername());
        ngUser.setPassword(null);//屏蔽密码
        httpServletRequest.getSession().setAttribute("user", ngUser);
    }
}
